package tech.cn.note.word.fun;

import cn.hutool.core.util.NumberUtil;
import com.deepoove.poi.render.compute.RenderDataCompute;

import org.springframework.stereotype.Service;

import static org.springframework.util.ObjectUtils.isEmpty;

@Service
public class Precision implements RenderFunction {
    /**
     * @param fields            参数1 数字
     * @param renderDataCompute
     * @return
     */
    @Override
    public String doCalculate(String[] fields, RenderDataCompute renderDataCompute) {
        if (isEmpty(fields)) {
            return "";
        }

        return getPointNum(fields[0], renderDataCompute);
    }

    private String getPointNum(String field, RenderDataCompute renderDataCompute) {
        if (NumberUtil.isNumber(field)) {
            Integer pointNum = Integer.parseInt(field);
            return doformat(pointNum);
        } else {
            Integer pointNum = Integer.parseInt(renderDataCompute.compute(field) + "");
            return doformat(pointNum);
        }
    }

    private String doformat(Integer pointNum) {
        StringBuffer strDefinition = new StringBuffer("0");
        if (pointNum < 1) {
            return strDefinition.toString();
        }
        strDefinition.append(".");
        for (int i = 0; i < pointNum; i++) {
            if (i == pointNum - 1) {
                strDefinition.append("1");
            } else {
                strDefinition.append("0");
            }

        }
        return strDefinition.toString();
    }
}
